//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.SessionMessages
{
    using System;
    using System.Collections.Generic;
    using System.ServiceModel;

    public class SessionReceiver
    {
        static void Main(string[] args)
        {
            try
            {
                // Create MessageReceiver for queue which requires session
                Console.Title = "Order Service";
                Console.WriteLine("Ready to receive messages from {0}...", SampleManager.OrderQueueName);

                // Creating the service host object as defined in config
                ServiceHost serviceHost = new ServiceHost(typeof(OrderService));

                // Add ErrorServiceBehavior for handling errors encounter by servicehost during execution.
                serviceHost.Description.Behaviors.Add(new ErrorServiceBehavior());

                // Subscribe to the faulted event.
                serviceHost.Faulted += new EventHandler(serviceHost_Faulted);

                // Start service
                serviceHost.Open();

                Console.WriteLine("\nPress [Enter] to close ServiceHost.");
                Console.ReadLine();

                // Close the service
                serviceHost.Close();
            }
            catch (Exception exception)
            {
                SampleManager.ExceptionOccurred = true;
                Console.WriteLine("Exception occurred: {0}", exception);
                Console.WriteLine("\nPress [Enter] to exit.");
                Console.ReadLine();
            }
        }

        static void serviceHost_Faulted(object sender, EventArgs e)
        {
            Console.WriteLine("Fault occurred. Aborting the service host object ...");
            ((ServiceHost)sender).Abort();
        }
    }
}
